<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="spuName">
        <el-input
          v-model="queryParams.spuName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属分类" prop="catalogId">
        <categoryCascader @handleChange="queryHandleChange" ref="queryCascader" v-model="queryParams.catalogId" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandId">
        <el-select size="small"v-model="queryParams.brandId" filterable placeholder="请选择">
          <el-option
            v-for="dict in brandList"
            :key="dict.brandId"
            :label="dict.brandName"
            :value="dict.brandId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in publishStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mall:spuInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mall:spuInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['mall:spuInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['mall:spuInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spuInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="id" v-if="false"/>
      <el-table-column label="商品名称" align="center" prop="spuName" />
      <el-table-column label="商品描述" align="center" prop="spuDescription" />
      <el-table-column label="所属分类" align="center" prop="catalogName" />
      <el-table-column label="品牌" align="center" prop="brandName" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column label="状态" align="center" prop="publishStatus">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.publishStatus==1">上架</el-tag>
          <el-tag type="info" v-else-if="scope.row.publishStatus==0">下架</el-tag>
          <el-tag type="warning" v-else>新建</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['mall:spuInfo:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateAttr(scope.row)"
            >规格参数</el-button>
          </el-row>
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['mall:spuInfo:remove']"
            >删除</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-tickets"
              @click="handleSkuList(scope.row)"
            >商品列表</el-button>
          </el-row>
          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="upSpuInfo(scope.row)"
              v-if="scope.row.publishStatus==0||scope.row.publishStatus==2"
            >上架</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="upSpuInfo(scope.row)"
              v-else-if="scope.row.publishStatus==1"
            >下架</el-button>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改spu信息对话框 -->
    <el-dialog :title="title" v-if="open" :close-on-click-modal="false" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="spuName">
          <el-input v-model="form.spuName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input v-model="form.spuDescription" placeholder="商品描述" />
        </el-form-item>
        <el-form-item label="所属分类" prop="catalogId">
          <categoryCascader v-if="cascaderShow" @handleChange="handleChange" :size="cascaderSize" :cascaderWidth="cascaderWidth" :catelogPath="catalogIds"/>
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select v-model="form.brandId" filterable placeholder="请选择">
            <el-option
              v-for="dict in addOrUpdateBrandList"
              :key="dict.brandId"
              :label="dict.brandName"
              :value="dict.brandId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="上架状态">
          <el-radio-group v-model="form.publishStatus">
            <el-radio
              v-for="dict in publishStatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <attrUpdate :catalogId="catalogId" :openAttrDialogProp="openAttr" :spuId="spuId"/>
  </div>
</template>

<script>
import { listSpuInfo, getSpuInfo, delSpuInfo, addSpuInfo, updateSpuInfo, exportSpuInfo,upSpuInfo } from "@/api/mall/pms/spuInfo";
import ImageUpload from '@/components/ImageUpload';
import attrUpdate from './attrUpdate';
import categoryCascader from '@/views/components/category-cascader';
import {queryListByCatelogId } from "@/api/mall/pms/categoryBrand";
import {queryBrandList} from "@/api/mall/pms/brand";
export default {
  name: "SpuInfo",
  components: {
    ImageUpload,
    categoryCascader,
    attrUpdate
  },
  data() {
    return {
      openAttr:false,
      //级联样式
      cascaderShow:false,
    cascaderSize:"medium",
      cascaderWidth:"300px",
	  //按钮loading
	  buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // spu信息表格数据
      spuInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上架状态[0 - 下架，1 - 上架]字典
      publishStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spuName: undefined,
        catalogId: undefined,
        brandId: undefined,
        publishStatus: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        spuName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        spuDescription: [
          { required: true, message: "商品描述不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌名称不能为空", trigger: "blur" }
        ],
        weight: [
          { required: true, message: "重量不能为空", trigger: "blur" }
        ],
        publishStatus: [
          { required: true, message: "上架状态不能为空", trigger: "blur" }
        ],
      },
      //品牌集合
      brandList:[],
      addOrUpdateBrandList:[],
      //分类id
      catalogId:'',
      spuId:'',
      catalogIds:[],
    };
  },
  created() {
    this.getList();
    this.queryBrandList();
    this.getDicts("mall_status").then(response => {
      this.publishStatusOptions = response.data;
    });
  },
  methods: {
    //打开规格参数
    handleUpdateAttr(row){
      this.openAttr=false;
      this.$nextTick(()=>{
        this.openAttr=true;
        this.catalogId=row.catalogId
        this.spuId=row.id
      })

    },
    //上架
    upSpuInfo(row){
      this.$confirm('是否确认上架?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        upSpuInfo(row.id).then(response=>{
          if(response.code==200){
            this.getList();
            this.msgSuccess("上架成功");
          }
        })
      }).catch(() => {
      });
    },
    //选择关联的分类
    handleChange(data){
      this.catalogIds=data;
      this.catalogId=data[data.length-1]
      this.form.brandId=''
      this.addOrUpdateBrandListFn(this.catalogId);
    },
    //品牌列表
    addOrUpdateBrandListFn(catalogId){
      queryListByCatelogId(catalogId).then(response => {
        this.addOrUpdateBrandList = response.data;
      }).catch(() => {
      });
    },
    //sku列表
    handleSkuList(row){
      this.$router.push("/mall/skuInfo/" + row.id);
    },
    //查询
    queryHandleChange(data){
      this.queryParams.catalogId=data[data.length-1];
      this.queryBrandListByCatelogId(this.queryParams.catalogId);
    },
    /** 按分类id查询品牌 */
    queryBrandListByCatelogId(catalogId) {
      this.queryParams.brandId=''
      queryListByCatelogId(catalogId).then(response => {
        this.brandList = response.data;
      }).catch(() => {
      });
    },
    /** 查询品牌 */
    queryBrandList() {
      this.queryParams.brandId=''
      queryBrandList().then(response => {
        this.brandList=[]
        response.data.forEach(e=>{
           let brand = {
             brandId:e.brandId,
             brandName:e.name
           }
          this.brandList.push(brand)
        })
      }).catch(() => {
      });
    },

    /** 查询spu信息列表 */
    getList() {
      this.loading = true;
      listSpuInfo(this.queryParams).then(response => {
        this.spuInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 上架状态[0 - 下架，1 - 上架]字典翻译
    publishStatusFormat(row, column) {
      return this.selectDictLabel(this.publishStatusOptions, row.publishStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        spuName: undefined,
        spuDescription: undefined,
        catalogId: undefined,
        brandId: undefined,
        weight: undefined,
        publishStatus: 0,
        createTime: undefined,
        updateTime: undefined
      };
      this.catalogIds=[]
      this.addOrUpdateBrandList=[]
      this.cascaderShow=false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.queryBrandList();
      this.$refs.queryCascader.resetHandle()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加spu信息";
      this.cascaderShow=true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.cascaderShow=true;
      const id = row.id || this.ids
      getSpuInfo(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.catalogIds=response.data.catalogIds;
        this.addOrUpdateBrandListFn(response.data.catalogId)
        this.open = true;
        this.title = "修改spu信息";
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.catalogId=this.catalogIds[this.catalogIds.length-1];
          if(this.form.catalogId===''||this.form.catalogId==null){
            this.msgWarning("所属分类不能为空")
            return false;
          }
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateSpuInfo(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {
               this.buttonLoading = false;
            });
          } else {
            addSpuInfo(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除spu信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delSpuInfo(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有spu信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportSpuInfo(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {
          this.exportLoading = false;
        });
    }
  }
};
</script>
